﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TjZheng.Windows.Forms;
using TjZheng.Framework;
using TjZheng.Logging;
using System.Text.RegularExpressions;
using System.IO;
using TjZheng.JiaLi.Process;
using TjZheng.Core.Mvc;

namespace TjZheng.JiaLi.Winform
{
    public partial class JiaLiForm1_1 : TicketForm
    {
        public JiaLiForm1_1()
        {
            InitializeComponent();
            this.TicketProcessHandler.PrintMessage += this.ShowMessage;
            this.TicketProcessHandler.PgaeIndexChange += (objJiaLiProcessContext) => 
            {
                this.CurrentSynchronizationContext.Post((state) =>
                {
                    if (objJiaLiProcessContext.PageIndex != objJiaLiProcessContext.PageCount)
                    {
                        Txt_StartPage.Text = (objJiaLiProcessContext.PageIndex + 1).ToString();
                    }
                    objJiaLiProcessContext.PageIndex++;
                },null);
            };
            this.Text = this.TicketContext.FormTitle;
            this.Txt_IndexUrl.Text = this.TicketContext.TargetUrl;
            this.Txt_PageUrl.Text = this.TicketContext.PageUrlFormat;
            this.Txt_SingleUrl.Text = this.TicketContext.SingleUrl;
            this.Txt_Dir.Text = this.TicketContext.Directory;

            ThreadPool.SetMinThreads(8, 8);
            ThreadPool.SetMaxThreads(16, 16);
        }

        public override TicketProcessHandler CreateTicketProcessHandler()
        {
            return Reflector.CreateInstace<TicketProcessHandler>(ConfigHelper.GetValue("RunVersion"), "TjZheng.JiaLi.Process");
        }

        public override TicketContext CreateTicketContext()
        {
            return Reflector.CreateInstace<TicketContext>(ConfigHelper.GetValue("RunContext"), "TjZheng.JiaLi.Process");
        }

        public override void ShowMessage(object message)
        {
            this.CurrentSynchronizationContext.Post((state) =>
            {
                Rtxt_Message.AppendText(Convert.ToString(state));
                Rtxt_Message.SelectionStart = Rtxt_Message.TextLength;
                Rtxt_Message.ScrollToCaret();
            }, message.CreateMessage() + "\r\n");
        }

        private void Btn_Start_Click(object sender, EventArgs e)
        {
            if (!Txt_StartPage.Text.IsMatch(@"^\d+$"))
            {
                base.ShowMessage("对不起，请输入正确的起始页码");
                return;
            }
            if (!Txt_EndPage.Text.IsMatch(@"^\d+$"))
            {
                base.ShowMessage("对不起，请输入正确的终点页码");
                return;
            }
            if (Txt_Dir.Text.IsNull())
            {
                base.ShowMessage("请选择下载目录");
                return;
            }

            this.TicketContext.IsStop = false;
            this.TicketContext.IsAsync = Rb_Async.Checked;
            this.TicketContext.IsBatch = Rb_Batch.Checked;
            this.TicketContext.ErrorRepeat = Rb_Repeat5.Checked ? 5 : 10;
            this.TicketContext.WritePath = Txt_Dir.Text;

            if (this.TicketContext.IsBatch)
            {
                int pageIndex = Convert.ToInt32(Txt_StartPage.Text.Trim());
                int pageCount = Convert.ToInt32(Txt_EndPage.Text.Trim());
                if (pageIndex > pageCount)
                {
                    base.ShowMessage("对不起，起始页码不能超过终点页码");
                    return;
                }
                this.TicketContext.PageIndex = pageIndex;
                this.TicketContext.PageCount = pageCount;

                this.TicketContext.TargetUrl = this.Txt_IndexUrl.Text.Trim();
                this.TicketContext.PageUrlFormat = this.Txt_PageUrl.Text.Trim();
            }
            else
            {
                this.TicketContext.SingleUrl = this.Txt_SingleUrl.Text.Trim();
            }

            Btn_Start.Enabled = false;
            Btn_Continue.Enabled = false;
            Btn_Restart.Enabled = false;

            this.DisableControls();

            ProcessContext objProcessContext = new ProcessContext("StartCatchImages", this.TicketContext);
            ThreadPool.QueueUserWorkItem((state) => 
            {
                this.TicketProcessHandler.ExecuteProcess(objProcessContext);
            });
        }

        private void Btn_Stop_Click(object sender, EventArgs e)
        {
            this.TicketContext.IsStop = true;
            this.Btn_Stop.Text = "正在停止";
            ThreadPool.QueueUserWorkItem((state1) =>
            {
                this.CurrentSynchronizationContext.Post((state2) =>
                {
                    while (this.TicketProcessHandler.ConcurrentQueue.Count > 0)
                    {
                    }
                    Btn_Start.Enabled = true;
                    Btn_Continue.Enabled = true;
                    Btn_Restart.Enabled = true;
                    this.EnableControls();
                    this.Btn_Stop.Text = "停止下载";
                }, null);
            });

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        private void Btn_Continue_Click(object sender, EventArgs e)
        {
            if (!Txt_StartPage.Text.IsMatch(@"^\d+$"))
            {
                base.ShowMessage("对不起，请输入正确的起始页码");
                return;
            }
            if (!Txt_EndPage.Text.IsMatch(@"^\d+$"))
            {
                base.ShowMessage("对不起，请输入正确的终点页码");
                return;
            }
            if (Txt_Dir.Text.IsNull())
            {
                base.ShowMessage("请选择下载目录");
                return;
            }

            this.TicketContext.IsStop = false;
            this.TicketContext.IsAsync = Rb_Async.Checked;
            this.TicketContext.IsBatch = Rb_Batch.Checked;
            this.TicketContext.ErrorRepeat = Rb_Repeat5.Checked ? 5 : 10;
            this.TicketContext.WritePath = Txt_Dir.Text;

            if (this.TicketContext.IsBatch)
            {
                int pageIndex = Convert.ToInt32(Txt_StartPage.Text.Trim());
                int pageCount = Convert.ToInt32(Txt_EndPage.Text.Trim());
                if (pageIndex > pageCount)
                {
                    base.ShowMessage("对不起，起始页码不能超过终点页码");
                    return;
                }
                this.TicketContext.PageIndex = pageIndex;
                this.TicketContext.PageCount = pageCount;

                this.TicketContext.TargetUrl = this.Txt_IndexUrl.Text.Trim();
                this.TicketContext.PageUrlFormat = this.Txt_PageUrl.Text.Trim();
            }
            else
            {
                this.TicketContext.SingleUrl = this.Txt_SingleUrl.Text.Trim();
            }

            Btn_Start.Enabled = false;
            Btn_Continue.Enabled = false;
            Btn_Restart.Enabled = false;

            this.DisableControls();

            ProcessContext objProcessContext = new ProcessContext("StartCatchImages", this.TicketContext);
            ThreadPool.QueueUserWorkItem((state) =>
            {
                this.TicketProcessHandler.ExecuteProcess(objProcessContext);
            });
        }

        private void Btn_Restart_Click(object sender, EventArgs e)
        {
            if (!Txt_StartPage.Text.IsMatch(@"^\d+$"))
            {
                base.ShowMessage("对不起，请输入正确的起始页码");
                return;
            }
            if (!Txt_EndPage.Text.IsMatch(@"^\d+$"))
            {
                base.ShowMessage("对不起，请输入正确的终点页码");
                return;
            }
            if (Txt_Dir.Text.IsNull())
            {
                base.ShowMessage("请选择下载目录");
                return;
            }

            this.TicketContext.IsStop = false;
            this.TicketContext.IsAsync = Rb_Async.Checked;
            this.TicketContext.IsBatch = Rb_Batch.Checked;
            this.TicketContext.ErrorRepeat = Rb_Repeat5.Checked ? 5 : 10;
            this.TicketContext.WritePath = Txt_Dir.Text;

            if (this.TicketContext.IsBatch)
            {
                int pageIndex = Convert.ToInt32(Txt_StartPage.Text.Trim());
                int pageCount = Convert.ToInt32(Txt_EndPage.Text.Trim());
                if (pageIndex > pageCount)
                {
                    base.ShowMessage("对不起，起始页码不能超过终点页码");
                    return;
                }
                this.TicketContext.PageIndex = pageIndex;
                this.TicketContext.PageCount = pageCount;

                this.TicketContext.TargetUrl = this.Txt_IndexUrl.Text.Trim();
                this.TicketContext.PageUrlFormat = this.Txt_PageUrl.Text.Trim();
            }
            else
            {
                this.TicketContext.SingleUrl = this.Txt_SingleUrl.Text.Trim();
            }

            Btn_Start.Enabled = false;
            Btn_Continue.Enabled = false;
            Btn_Restart.Enabled = false;
            Rtxt_Message.Text = "";

            this.DisableControls();

            ProcessContext objProcessContext = new ProcessContext("StartCatchImages", this.TicketContext);
            ThreadPool.QueueUserWorkItem((state) =>
            {
                this.TicketProcessHandler.ExecuteProcess(objProcessContext);
            });
        }

        private void Btn_SelectDir_Click(object sender, EventArgs e)
        {
            string selectDirectory = SelectDirectory();
            if (selectDirectory.IsNoNull())
            {
                Txt_Dir.Text = selectDirectory;
            }
        }

        private void www5542comForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.TicketContext.IsStop = true;

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        private void EnableControls()
        {
            foreach (Control objControl in this.Controls)
            {
                if (objControl is CheckBox)
                {
                    CheckBox objCheckBox = objControl as CheckBox;
                    objCheckBox.Enabled = true;
                }
                else if (objControl is TextBox)
                {
                    TextBox objTextBox = objControl as TextBox;
                    objTextBox.Enabled = true;
                }
                else if (objControl is GroupBox)
                {
                    GroupBox objGroupBox = objControl as GroupBox;
                    objGroupBox.Enabled = true;
                }
            }
        }

        private void DisableControls()
        {
            foreach (Control objControl in this.Controls)
            {
                if (objControl is CheckBox)
                {
                    CheckBox objCheckBox = objControl as CheckBox;
                    objCheckBox.Enabled = false;
                }
                else if (objControl is TextBox)
                {
                    TextBox objTextBox = objControl as TextBox;
                    objTextBox.Enabled = false;
                }
                else if (objControl is GroupBox)
                {
                    GroupBox objGroupBox = objControl as GroupBox;
                    objGroupBox.Enabled = false;
                }
            }
        }
    }
}
